package com.manager.devicemanager.controller;


import com.alibaba.fastjson2.JSONObject;
import com.manager.devicemanager.annotation.OperateLog;
import com.manager.devicemanager.common.OperationTypeEnum;
import com.manager.devicemanager.common.Result;
import com.manager.devicemanager.config.ActiveMQListener;
import com.manager.devicemanager.config.ActiveMqConfig;
import com.manager.devicemanager.util.MqProducer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/mqtt")
public class MqttMessageController {
    @Autowired
    private  MqProducer mqProducer;
    @Autowired
    private ActiveMQListener activeMQListener;


    /**
     * 接收 HTTP POST 请求，将请求体中的消息发送到 MQTT 代理
     *
     * @return 发送成功的提示信息
     */
    @OperateLog(operationType = OperationTypeEnum.CONTROL, operationDesc = "设备操控")
    @PostMapping("/send-control")
    public Result<String> sendMqtt(@RequestBody JSONObject config) {
        try {
            String mqttMessage = config.getString("message");
//        DeviceLog deviceLog = new DeviceLog();
//        System.out.println(mqttMessage);
            String mqttindex = config.getString("datasourceindex");
            String type = config.getString("type");
            if ("ic".equals(type)) {
                if ("".equals(mqttindex)) {
                    mqProducer.sendStringTopic(activeMQListener.publishICTopic,mqttMessage);
                } else if ("1".equals(mqttindex)) {
                    mqProducer.sendStringTopic(activeMQListener.publishIC2Topic,mqttMessage);
                } else {
                    return Result.error("MQTT message topic 未配置");
                }
            } else if ("pd".equals(type)) {
                mqProducer.sendStringTopic(activeMQListener.publishPDTopic,mqttMessage);
            }


            return Result.success("MQTT message sent successfully");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("MQTT message sent failed");
        }
    }


}
